package model.expression.command;

import java.util.Stack;

import model.expression.AbstractExpression;
import model.expression.operator.LeftBracExpression;
import model.expression.operator.RightBracExpression;
import model.parser.ParserException;
import state.TabState;

public class If extends AbstractCommandExpression {

	public If(TabState ts) {
		super(ts);
	}
	
	public  void addChildrenFrom(Stack<AbstractExpression> out){
		if(out.empty()){
			throw ParserException.BAD_ARGUMENTS;
		}
		while(!out.isEmpty()){
			AbstractExpression node = out.pop();
			if (node instanceof LeftBracExpression)
				continue;
			if (node instanceof RightBracExpression)
				break;
			this.children.add(node);	
		}
	}
	
	@Override
	protected int getExpNumChildren() {
		throw ParserException.INTERNAL_ERROR;
	}

	@Override
	public int evaluate() {
		
		int firstActiveTurtleReturnState = 0;
		
		//for each turtle, record the lastReturn value for the first active turtle
		for (int i = 0; i < tabSt.getActiveTurtle().size(); i++) {
			//if it is the first active turtle
			if (i == 0){
				firstActiveTurtleReturnState = (int) this.children.get(0).evaluate();
				if (firstActiveTurtleReturnState != 0)
					for (int k = 1; k < this.children.size(); k++)
						this.children.get(k).evaluate();
			}
			else{
				if ((int) this.children.get(0).evaluate() != 0)
					for (int k = 1; k < this.children.size(); k++)
						this.children.get(k).evaluate();
			}
		}
		return firstActiveTurtleReturnState;
	}
}
